//
//  FTInternationalizationManager.m
//  FTInternationalizationManager
//
//  Created by JackieYip on 2017/6/11.
//  Copyright © 2017年 mondial-d. All rights reserved.
//

#import "FTInternationalizationManager.h"

// Component_FTBundle
#import "FTMediator+FTBundle.h"

#define kAppLanguageKey     @"kAppLanguageKey"
#define kAppCurrencyKey     @"kAppCurrencyKey"
#define kAppleLanguageKey   @"AppleLanguages"
#define kAppleLocaleKey     @"AppleLocale"



// app默认语言：简体中文
static NSString *const kAppDefaultLanguage = @"zh-Hans";

@interface FTInternationalizationManager ()
@property (strong, nonatomic, readwrite) NSLocale *languageLocale;
@property (strong, nonatomic, readwrite) NSLocale *currencyLocale;
// app支持的语言：简体中文、英文
@property (strong, nonatomic, readwrite) NSMutableArray *appSupportLanguages;
// app支持的货币：人民币、港币、美元（暂时不支持美元）
@property (strong, nonatomic, readwrite) NSMutableArray *appSupportCurrencys;
// app支持的电话国家代号：中国大陆、香港、澳门、台湾、新加坡、美国、加拿大、英国、法国、澳大利亚、日本
@property (strong, nonatomic, readwrite) NSMutableArray *appSupportPhoneLoales;
// 保存：苹果系统语言
@property (strong, nonatomic, readwrite) NSArray *appleSystemLanguages;
// 苹果商店区域
@property (strong, nonatomic, readwrite) NSString *appStoreArea;
@end

@implementation FTInternationalizationManager

+(instancetype)sharedManager
{
    static FTInternationalizationManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[FTInternationalizationManager alloc] init];
    });
    return shareManager;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self initAppLanguageOnResponse:nil];
    }
    return self;
}

- (void)initAppLanguageOnResponse:(void (^)(FTLanguageIndex currentLanguageIndex))onResponse
{
    // 初始化：语言
    [self innerInitAppLanguage];
    
    // 初始化：货币
    [self innerInitAppCurrency];
    
    // 设置：bundle
    [self innerSetBundle];
    
    if (onResponse)
        onResponse([self currentLanguageIndex]);
    
}

- (void)innerInitAppLanguage
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    __block NSString *appCurrentLanguage = [userDefaults valueForKey:kAppLanguageKey];
    self.languageLocale = [NSLocale localeWithLocaleIdentifier:appCurrentLanguage];
    // app未设置语言，则设置 appCurrentLanguage
    if (appCurrentLanguage.length == 0) {
        // 获取:系统语言
        self.appleSystemLanguages = [NSArray arrayWithArray:[userDefaults objectForKey:kAppleLanguageKey]];
        
        __block BOOL didSetAppLanguage = NO;
        // 遍历：系统语言
        [self.appleSystemLanguages enumerateObjectsUsingBlock:^(NSString * _Nonnull systemLanguage, NSUInteger idx, BOOL * _Nonnull stop) {
            // 遍历：app支持语言
            [self.appSupportLanguages enumerateObjectsUsingBlock:^(NSString * _Nonnull appLanguage, NSUInteger languageIndex, BOOL * _Nonnull stop) {
                // 判断：app支持该系统语言
                if ([systemLanguage hasPrefix:appLanguage]) {
                    // 设置：使用该系统语言
                    appCurrentLanguage = appLanguage;
                    [userDefaults setValue:appCurrentLanguage forKey:kAppLanguageKey];
                    self.languageLocale = [NSLocale localeWithLocaleIdentifier:appCurrentLanguage];
                    // 设置：系统语言key
                    NSMutableArray *newSystemLanguages = [NSMutableArray arrayWithArray:self.appleSystemLanguages];
                    NSMutableArray *waitForRemove = [NSMutableArray array];
                    [newSystemLanguages enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj hasPrefix:appCurrentLanguage])
                            [waitForRemove addObject:obj];
                    }];
                    [newSystemLanguages removeObjectsInArray:waitForRemove];
                    [newSystemLanguages insertObject:appCurrentLanguage atIndex:0];
                    while (newSystemLanguages.count > 6) {
                        [newSystemLanguages removeLastObject];
                    }
                    self.appleSystemLanguages = newSystemLanguages;
                    [userDefaults setValue:newSystemLanguages forKey:kAppleLanguageKey];
                    
                    didSetAppLanguage = YES;
                    
                    *stop = YES;
                }
            }];
            if (didSetAppLanguage)
                *stop = YES;
        }];
        
        // 判断：app不支持该系统语言
        if (!didSetAppLanguage) {
            // 设置：使用默认语言
            appCurrentLanguage = kAppDefaultLanguage;
            // 设置：系统语言key
            NSMutableArray *newSystemLanguages = [NSMutableArray arrayWithArray:self.appleSystemLanguages];
            NSMutableArray *waitForRemove = [NSMutableArray array];
            [newSystemLanguages enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj hasPrefix:appCurrentLanguage])
                    [waitForRemove addObject:obj];
            }];
            [newSystemLanguages removeObjectsInArray:waitForRemove];
            [newSystemLanguages insertObject:appCurrentLanguage atIndex:0];
            while (newSystemLanguages.count > 6) {
                [newSystemLanguages removeLastObject];
            }
            self.appleSystemLanguages = newSystemLanguages;
            [userDefaults setValue:appCurrentLanguage forKey:kAppLanguageKey];
            [userDefaults setValue:newSystemLanguages forKey:kAppleLanguageKey];
            self.languageLocale = [NSLocale localeWithLocaleIdentifier:appCurrentLanguage];
            
        }
    }
}

- (void)innerInitAppCurrency
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    __block NSString *appCurrentCurrency = [userDefaults valueForKey:kAppCurrencyKey];
    self.currencyLocale = [NSLocale localeWithLocaleIdentifier:appCurrentCurrency];
    // app未设置货币，则设置 appCurrentCurrency
    if (appCurrentCurrency.length == 0) {
        // 当前英文站:港币
        if (self.isENLanguage)
            appCurrentCurrency = self.appSupportCurrencys[FTCurrencyIndex_HKD];
        // 其他站：人民币
        else
            appCurrentCurrency = self.appSupportCurrencys[FTCurrencyIndex_CNY];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:appCurrentCurrency forKey:kAppCurrencyKey];
        [userDefaults synchronize];
        self.currencyLocale = [NSLocale localeWithLocaleIdentifier:appCurrentCurrency];
    }
}

- (void)setAppLanguage:(NSString *)language isManuallySetup:(BOOL)isManuallySetup onResponse:(void (^)(BOOL shouldSetLanguageToRemoteServer, FTLanguageIndex currentLanguageIndex))onResponse
{
    [self setAppLanguage:language andAppCurrency:nil isManuallySetup:isManuallySetup onResponse:onResponse];
}

- (void)setAppCurrency:(NSString *)currency isManuallySetup:(BOOL)isManuallySetup onResponse:(void (^)(BOOL shouldSetLanguageToRemoteServer, FTLanguageIndex currentLanguageIndex))onResponse
{
    [self setAppLanguage:nil andAppCurrency:currency isManuallySetup:isManuallySetup onResponse:onResponse];
}

- (void)setAppLanguage:(NSString *)language andAppCurrency:(NSString *)currency isManuallySetup:(BOOL)isManuallySetup onResponse:(void (^)(BOOL shouldSetLanguageToRemoteServer, FTLanguageIndex currentLanguageIndex))onResponse
{
    BOOL shouldSetLanguageToRemoteServer = NO;
    // 同时设置语言、货币
    if (language.length > 0 && currency.length > 0) {
        // 语言未变
        if ([language isEqualToString:self.languageLocale.localeIdentifier])
            return;
        // 语言不支持
        if (![self.appSupportLanguages containsObject:language])
            return;
        // 货币未变
        //        if ([currency isEqualToString:self.currencyLocale.localeIdentifier])
        //            return;
        // 货币不支持
        if (![self.appSupportCurrencys containsObject:currency])
            return;
        
        // 设置：使用该语言
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:language forKey:kAppLanguageKey];
        // 设置：系统语言key
        NSMutableArray *newSystemLanguages = [NSMutableArray arrayWithArray:self.appleSystemLanguages];
        NSMutableArray *waitForRemove = [NSMutableArray array];
        [newSystemLanguages enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj hasPrefix:language])
                [waitForRemove addObject:obj];
        }];
        [newSystemLanguages removeObjectsInArray:waitForRemove];
        [newSystemLanguages insertObject:language atIndex:0];
        while (newSystemLanguages.count > 6) {
            [newSystemLanguages removeLastObject];
        }
        self.appleSystemLanguages = newSystemLanguages;
        [userDefaults setValue:newSystemLanguages forKey:kAppleLanguageKey];
        
        [userDefaults synchronize];
        self.languageLocale = [NSLocale localeWithLocaleIdentifier:language];
        
        // 回调：设置语言到远程服务器，可在回调中处理其他业务需求
        shouldSetLanguageToRemoteServer = YES;
        if (onResponse) {
            onResponse(shouldSetLanguageToRemoteServer, [self currentLanguageIndex]);
        }
        
        // 设置：货币
        [userDefaults setValue:currency forKey:kAppCurrencyKey];
        [userDefaults synchronize];
        self.currencyLocale = [NSLocale localeWithLocaleIdentifier:currency];
        
        // 设置：bundle
        [self innerSetBundle];
    }
    // 仅设置语言
    else if (language.length > 0) {
        // 语言未变
        if ([language isEqualToString:self.languageLocale.localeIdentifier])
            return;
        // 语言不支持
        if (![self.appSupportLanguages containsObject:language])
            return;
        
        // 设置：使用该语言
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:language forKey:kAppLanguageKey];
        // 设置：系统语言key
        NSMutableArray *newSystemLanguages = [NSMutableArray arrayWithArray:self.appleSystemLanguages];
        NSMutableArray *waitForRemove = [NSMutableArray array];
        [newSystemLanguages enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj hasPrefix:language])
                [waitForRemove addObject:obj];
        }];
        [newSystemLanguages removeObjectsInArray:waitForRemove];
        [newSystemLanguages insertObject:language atIndex:0];
        while (newSystemLanguages.count > 6) {
            [newSystemLanguages removeLastObject];
        }
        self.appleSystemLanguages = newSystemLanguages;
        [userDefaults setValue:newSystemLanguages forKey:kAppleLanguageKey];
        
        [userDefaults synchronize];
        self.languageLocale = [NSLocale localeWithLocaleIdentifier:language];
        
        // 回调：设置语言到远程服务器，可在回调中处理其他业务需求
        shouldSetLanguageToRemoteServer = YES;
        if (onResponse) {
            onResponse(shouldSetLanguageToRemoteServer, [self currentLanguageIndex]);
        }
        
        // 初始化：货币
        [self innerInitAppCurrency];
        
        // 设置：bundle
        [self innerSetBundle];
    }
    // 仅设置货币
    else if (currency.length > 0) {
        // 货币未变
        if ([currency isEqualToString:self.currencyLocale.localeIdentifier])
            return;
        // 货币不支持
        if (![self.appSupportCurrencys containsObject:currency])
            return;
        
        // 设置：使用该货币
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:currency forKey:kAppCurrencyKey];
        [userDefaults synchronize];
        self.currencyLocale = [NSLocale localeWithLocaleIdentifier:currency];
        
        // 回调：设置语言到远程服务器，可在回调中处理其他业务需求
        shouldSetLanguageToRemoteServer = NO;
        if (onResponse) {
            onResponse(shouldSetLanguageToRemoteServer, [self currentLanguageIndex]);
        }
    }
}

- (void)innerSetBundle
{
    [kFTMediator FTBundle_setupWithLanguageLocaleIdentifier:self.languageLocale.localeIdentifier];
}


#pragma mark - getter
- (NSMutableArray *)appSupportLanguages {
    if (!_appSupportLanguages) {
        // 设置：app支持语言
        self.appSupportLanguages = [NSMutableArray array];
        self.appSupportLanguages[FTLanguageIndex_cn] = @"zh-Hans";
        self.appSupportLanguages[FTLanguageIndex_en] = @"en";
    }
    return _appSupportLanguages;
}
- (NSMutableArray *)appSupportCurrencys {
    if (!_appSupportCurrencys) {
        // 设置：app支持的货币
        self.appSupportCurrencys = [NSMutableArray array];
        self.appSupportCurrencys[FTCurrencyIndex_CNY] = @"zh-Hans-CN";
        self.appSupportCurrencys[FTCurrencyIndex_HKD] = @"zh-Hant-HK";
        // 暂时不支持 美元
        self.appSupportCurrencys[FTCurrencyIndex_USD] = @"en-US";
    }
    return _appSupportCurrencys;
}
// app支持的电话国家代号：中国大陆、香港、澳门、台湾、新加坡、美国、加拿大、英国、法国、澳大利亚、日本
- (NSMutableArray *)appSupportPhoneLoales {
    if (!_appSupportPhoneLoales) {
        self.appSupportPhoneLoales = [NSMutableArray array];
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_CN] = @"CN";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_HK] = @"HK";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_MO] = @"MO";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_TW] = @"TW";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_SG] = @"SG";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_US] = @"US";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_CA] = @"CA";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_GB] = @"GB";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_FR] = @"FR";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_AU] = @"AU";
        self.appSupportPhoneLoales[FTPhoneLocaleIdex_JP] = @"JP";
    }
    return _appSupportPhoneLoales;
}
- (NSString *)countryLocaleIdentifier {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *appleLocaleString = [userDefaults valueForKey:kAppleLocaleKey];
    __block NSString *countryLocaleIdentifier = @"CN";
    [self.appSupportPhoneLoales enumerateObjectsUsingBlock:^(NSString * _Nonnull phoneLocale, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([[appleLocaleString uppercaseString] hasSuffix:phoneLocale]) {
            countryLocaleIdentifier = phoneLocale;
            *stop = YES;
        }
    }];
    return countryLocaleIdentifier;
}
- (NSString *)appStoreArea {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *appleLocaleString = [userDefaults valueForKey:kAppleLocaleKey];
    NSArray *appleLocaleArray = [appleLocaleString componentsSeparatedByString:@"_"];
    if (appleLocaleArray.count > 0)
        self.appStoreArea = [appleLocaleArray.lastObject uppercaseString];
    else
        self.appStoreArea = @"CN";
    return _appStoreArea;
}

#pragma mark - getter
- (BOOL)isENLanguage
{
    return [self.languageLocale.localeIdentifier hasPrefix:self.appSupportLanguages[FTLanguageIndex_en]];
}
- (BOOL)isCNLanguage
{
    return [self.languageLocale.localeIdentifier hasPrefix:self.appSupportLanguages[FTLanguageIndex_cn]];
}
- (FTLanguageIndex)currentLanguageIndex
{
    if (self.isENLanguage)
        return FTLanguageIndex_en;
    else
        return FTLanguageIndex_cn;
}

@end
